//
//  LeavewordMsgViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2017/4/19.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "LeavewordMsgViewController.h"
#import "LeaveMsgTopView.h"
#import "MessageCommentCell.h"
#import "CommentNoticeModel.h"
#import "CommentModel.h"

@interface LeavewordMsgViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    NSMutableArray *_replyleavelistArray;
    NSDictionary *_mainLeaveDict;
    UITextField *_msgInputFeild;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *msgInputView;
@property (nonatomic, strong) LeaveMsgTopView *leaveMsgTopView;
@property (nonatomic, copy) NSString *detail;
@property (nonatomic, copy) NSString *parentId;
@property (nonatomic, copy) NSString *parentudid;
//!< 数据页数.表示下次请求第几页的数据.
@property (assign, nonatomic) NSInteger page;
@property (nonatomic, assign) NSInteger maxPage;
@end

@implementation LeavewordMsgViewController


- (UIView *)msgInputView {
    if (!_msgInputView) {
        //输入框
        _msgInputView = [[UIView alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT -kNAV_HEIGHT- 50, kSCREEN_WIDTH, 50 )];
        _msgInputView.backgroundColor = [UIColor whiteColor];
        UIView *sepline = [[UIView alloc] init];
        [_msgInputView addSubview:sepline];
        sepline.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 0.5);
        sepline.backgroundColor = [UIColor cellLineColor];
        UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sendBtn.frame = CGRectMake(self.view.width - 15 - 50, 0, 50, 50);
        [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [sendBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [sendBtn setTitleColor:UIColorFromRGB(0x0ACCAC) forState:UIControlStateNormal];
        [sendBtn setBackgroundColor:[UIColor clearColor]];
        [sendBtn addTarget:self action:@selector(clickSend:) forControlEvents:UIControlEventTouchUpInside];
        
        _msgInputFeild = [[UITextField alloc] initWithFrame:CGRectMake(10,7.5,sendBtn.left - 20,30)];
        _msgInputFeild.backgroundColor = [UIColor clearColor];
        _msgInputFeild.returnKeyType = UIReturnKeySend;
        _msgInputFeild.borderStyle = UITextBorderStyleRoundedRect;
        _msgInputFeild.placeholder = @"留下你想说的";
        _msgInputFeild.delegate = self;
        _msgInputFeild.textColor = [UIColor blackColor];
        _msgInputFeild.font = [UIFont systemFontOfSize:14];
        
        [_msgInputView addSubview:_msgInputFeild];
        [_msgInputView addSubview:sendBtn];
        
    }
    return _msgInputView;
}
#pragma mark -- 留言详情
- (void)LeaveListRequest {

    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"cid":[self.commentNoticeModel.c_parent intValue] ?self.commentNoticeModel.c_parent :self.commentNoticeModel.cid, //
                           @"page":[NSNumber numberWithInteger:self.page]
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:KLeaveDetail];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [self endRefresh];
        if ([responseObject[@"code"] intValue] == 200) {
            if (1 == self.page) { // 说明是在重新请求数据
                [_replyleavelistArray removeAllObjects];
            }
            _mainLeaveDict = responseObject[@"data"];
            self.parentudid = _mainLeaveDict[@"c_udid"];
            self.parentId = _mainLeaveDict[@"cid"];
            if (!self.tableView) {
                [self creatTableView];
            }
            NSArray *array = responseObject[@"data"][@"list"];
            self.maxPage = ceilf([responseObject[@"data"][@"num"] floatValue]/20);
            for (NSDictionary *commentDict in array) {
                CommentModel *model = [[CommentModel alloc] initWithDict:commentDict];
                [_replyleavelistArray addObject:model];
                }
            }
            [self.tableView reloadData];
    } failureBlock:^(NSError *error) {
       [self endRefresh];
    } showHUD:NO];
}

//留言回复
- (void)replyLeaveRequest {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"cid":[kUSER_TYPE intValue] == 100 ? User_ID :self.commentNoticeModel.c_cid,
                           @"description":self.detail,
                           @"type":@"30",//留言回复
                           @"parent":self.parentId,
                           @"pudid":self.parentudid,
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kSendComment];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] == 200) {
            _msgInputFeild.text = nil;
            NSDictionary *newData = responseObject[@"data"][@"comment"];
            [self updateReplylistWithdata:newData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

- (void)updateReplylistWithdata:(NSDictionary *)dataDict {
    CommentModel *model = [[CommentModel alloc] init];
    model.c_udid = dataDict[@"c_uid"];
    model.cid = self.commentNoticeModel.c_cid;
    model.c_content = dataDict[@"c_content"];
    model.c_createtime = dataDict[@"c_createtime"];
    model.cnickname = dataDict[@"u_nickname"];
    model.pnickname = _mainLeaveDict[@"u_nickname"];
    model.c_parent = dataDict[@"c_parent"];
    model.c_parudid = dataDict[@"c_parudid"];
    [_replyleavelistArray addObject:model];
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}

/**
 *  停止刷新
 */
-(void)endRefresh{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpUI];
    [self setNav];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameDidChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

//监听键盘高度变化
-(void)keyboardFrameDidChange:(NSNotification*)notice
{
    NSDictionary * userInfo = notice.userInfo;
    NSValue * endFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endFrame = endFrameValue.CGRectValue;
    [UIView animateWithDuration:0.25 animations:^{
        _msgInputView.y = endFrame.origin.y - _msgInputView.height - kNAV_HEIGHT;
    }];
}

- (void)setNav {
    self.navigationItem.title = @"留言详情";
}

#pragma mark -- UI
- (void)setUpUI {
    _replyleavelistArray = [NSMutableArray arrayWithCapacity:1];
    _mainLeaveDict = [NSMutableDictionary dictionaryWithCapacity:1];
    self.page = 1;
    [self LeaveListRequest];
}
- (void)creatTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT-kNAV_HEIGHT - 50) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self LeaveListRequest];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.page ++;
        if (self.page == self.maxPage+1) {
            self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        } else {
            [self LeaveListRequest];
        }
    }];
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.msgInputView];
}

- (void)replyLeaveMsgTopView {
    self.leaveMsgTopView = [[NSBundle mainBundle] loadNibNamed:@"LeaveMsgTopView" owner:self options:nil].lastObject;
    self.tableView.tableHeaderView = self.leaveMsgTopView;
}
#pragma mark -- tableView 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _replyleavelistArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageCommentCell *cell = [MessageCommentCell loadNibCellWithTabelView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CommentModel *model = _replyleavelistArray[indexPath.row];
    cell.commentModel = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    self.leaveMsgTopView = [[NSBundle mainBundle] loadNibNamed:@"LeaveMsgTopView" owner:self options:nil].lastObject;
    [self.leaveMsgTopView.leaveuserIcon sd_setImageWithURL:[NSURL URLWithString:_mainLeaveDict[@"u_avatar"]] placeholderImage:kPlACE_ICON];
    self.leaveMsgTopView.leaveTime.text = _mainLeaveDict[@"c_createtime"];
    self.leaveMsgTopView.leaveuserName.text = _mainLeaveDict[@"u_nickname"];
    self.leaveMsgTopView.leaveContent.text = _mainLeaveDict[@"c_content"];
    return self.leaveMsgTopView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 60+[self mainLeaveHeight]+20;
}

- (CGFloat)mainLeaveHeight {
    CGSize maxSize = CGSizeMake(kSCREEN_WIDTH - 75, MAXFLOAT);
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14], NSForegroundColorAttributeName: [UIColor colorWithWhite:0.263 alpha:1.000]};
    CGSize textSize = [_mainLeaveDict[@"c_content"] boundingRectWithSize:maxSize
                                                    options:NSStringDrawingUsesLineFragmentOrigin
                                                 attributes:attributes
                                                    context:nil].size;
    CGSize richTextSize = CGSizeMake(textSize.width, textSize.height + 2);
    return richTextSize.height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CommentModel *model = _replyleavelistArray[indexPath.row];
    CGSize maxSize = CGSizeMake(kSCREEN_WIDTH - 79, MAXFLOAT);
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14], NSForegroundColorAttributeName: [UIColor colorWithWhite:0.263 alpha:1.000]};
    CGSize textSize = [model.c_content boundingRectWithSize:maxSize
                                                    options:NSStringDrawingUsesLineFragmentOrigin
                                                 attributes:attributes
                                                    context:nil].size;
    CGSize richTextSize = CGSizeMake(textSize.width, textSize.height + 2);
    return richTextSize.height + 20;
}

#pragma mark -- 发送评论回复
- (void)clickSend:(UIButton *)sender {
    [_msgInputFeild resignFirstResponder];
    if (_msgInputFeild.text.length) {
        self.detail = _msgInputFeild.text;
        [self replyLeaveRequest];
    } else {
        [self showTitle:@"请输入回复文字"];
    }
}

#pragma mark -- UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    if (_msgInputFeild.text.length) {
        self.detail = _msgInputFeild.text;
        [self replyLeaveRequest];
    } else {
        [self showTitle:@"请输入回复文字"];
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
